package com.token;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookiesUtils {

	/**
	 * 
	 * @Description: 保存cookie
	 * @param @param response
	 * @param @param name
	 * @param @param value
	 * @param @param time
	 * @param @return   
	 * @return HttpServletResponse  
	 * @throws
	 * @author limh
	 * @date 2017年4月18日
	 */
    public static HttpServletResponse setCookie(HttpServletResponse response, String name, String value,int time,boolean httpOnly) {
        // new一个Cookie对象,键值对为参数
        Cookie cookie = new Cookie(name, value);
        // tomcat下多应用共享
        cookie.setPath("/");
        //这里必须使用HttpOnly属性来防止Cookie被JavaScript读取，从而避免跨站脚本攻击（XSS攻击）
        cookie.setHttpOnly(httpOnly);
        // 如果cookie的值中含有中文时，需要对cookie进行编码，不然会产生乱码
        try {
            URLEncoder.encode(value, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //cookie in seconds
        cookie.setMaxAge(time);
        // 将Cookie添加到Response中,使之生效
        response.addCookie(cookie); // addCookie后，如果已经存在相同名字的cookie，则最新的覆盖旧的cookie
        return response;
    }
    
    /**
     * 
     * @Description: 将cookie封装到Map里面
     * @param @param request
     * @param @return   
     * @return Map<String,Cookie>  
     * @throws
     * @author limh
     * @date 2017年4月18日
     */
    private static Map<String, Cookie> ReadCookieMap(HttpServletRequest request) {
        Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }
    
    /**
     * 根据名字取出cookie的value
     */
    public static String getCookieValueByName(HttpServletRequest request, String name) {
    	Cookie[] cookies = request.getCookies();
    	String value = "";
        if (null != cookies) {
            for (Cookie cookie : cookies) {
            	if(cookie.getName().equals(name)){
            		value = cookie.getValue();
            		break;
            	}
            }
        }
        return value;
    }
}
